<template>
  <div>
    <h1>问卷管理</h1>
    <el-table :data="extendedTableData" height="500" style="width: 100%" :row-class-name="tableRowQuestionnaire">
      <el-table-column prop="title" label="问卷标题" width="180">
        <template #default="{ row }">
          <span 
            :class="{ 'editable-title': !row.isEditing }" 
            @dblclick="openRename(row)"
          >{{ row.title }}</span>
          <input 
            class="editable-input" 
            type="text" 
            v-model="row.tempTitle" 
            v-if="row.isEditing"
            @blur="handleTitleBlur(row)"
            @keyup.enter="handleTitleBlur(row)"
            @keyup.esc="cancelEdit(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="id" label="问卷id" width="180" />
      <el-table-column prop="status" label="发布状态" width="180" :formatter="formatStatus"/>
      <el-table-column prop="username" label="创建者" width="180"/>
      <el-table-column prop="operation" label="操作">
        <template #default="{ row }">
          <router-link to="/Statistics">
            <el-button link type="primary" size="small" @click="statisticSurvey(row.id,this.$router)">查看统计</el-button>
          </router-link>
          <el-button link type="primary" size="small" @click="deleteSurvey(row.id)">删除问卷</el-button>
          <el-button 
            link 
            type="primary" 
            size="small" 
            v-if="(row.status === 0)" 
            @click="postSurvey(row.id)"
          >发布问卷</el-button>   
          <el-button 
            link 
            type="primary" 
            size="small" 
            v-if="(row.status !== 3)&&(row.status !== 0)"
            @click="UnpostSurvey(row.id)"
          >截止问卷</el-button>
          <el-button 
            link 
            type="primary" 
            size="small" 
            v-if="(row.status === 2)"
            @click="touserSurvey(row.id)"
          >仅向用户开放问卷</el-button>
          <el-button 
            link 
            type="primary" 
            size="small" 
            v-if="(row.status === 1)"
            @click="toallSurvey(row.id)"
          >向所有人开放问卷</el-button>


        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref ,computed} from 'vue';
import request from '../utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { id } from 'element-plus/es/locales.mjs';

interface Questionnaire {
  title: string;
  id: integer;
  status: integer;
  userId: integer;
}

export default defineComponent({ 

  setup() {
    const extendedTableData = computed(() => tableData.value.map(item => ({
      ...item,
      isEditing: false,
      tempTitle: item.title
    })));
    const tableData= ref<Questionnaire[]>([]);
    const renameDialogVisible = ref(true);
    const renameForm = ref({ id: 0, title: '' });
    
    const openRename = (row) => {
      row.isEditing = true;
      row.tempTitle = row.title;
    };

    const handleTitleBlur = async (row) => {
      row.isEditing = false;
      try {
        console.log(row.tempTitle,"     ",row.id);
        const response = await request.put('api/survey/update', null, {
          params: {
            id: row.id,
            title: row.tempTitle,
          }
        });
        if (response.code === "200") {
          ElMessage.success('问卷名称修改成功');
          row.title = row.tempTitle; 
          load();
        } else {
          ElMessage.error(response.msg || '名称修改失败');
        }
      } catch (error) {
        ElMessage.error('名称修改失败');
      }
    };

    const cancelEdit = (row) => {
      row.isEditing = false;
      row.tempTitle = row.title; // 取消编辑，恢复原标题
    };

    const load = async () => {
      const config = {
        method: 'get',
        url: 'api/survey/select',
      };

      try {
        
        const response = await request(config);
        if (response.code === '200') {
          tableData.value = response.data.map(item => {
            const { questions, ...rest } = item;
            return rest;
          });
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        ElMessage.error('Failed to fetch data');
      }
    };

    const deleteSurvey = async (Rid:number) => {
      console.log(Rid);
      const config_delete = {
        method: 'delete',
        url: 'api/survey/delete',
        data: {
          id:Rid
        }
      };
      ElMessageBox.confirm('确定删除该问卷?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await request.delete('api/survey/delete',{
            params:{
              id:Rid,
            }
          }
          ).then(res=>{
          if (response.code === '200') {
            console.log(/*config_delete.data.id*/"2222");
            const index = tableData.value.findIndex(item => item.id === id);
            if (index !== -1) {
              tableData.value.splice(index, 1);
              ElMessage.success('问卷删除成功');
            } else {
              ElMessage.error('未找到对应问卷');
            }
            load();
            ElMessage.success('问卷删除成功');
          } else {
            ElMessage.error(response.msg || '删除失败');
          }
        })
      } 
        catch (error) {
          ElMessage.success('问卷删除成功');
          console.log(Rid);
          load();
        }
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    };

    const statisticSurvey = async (id,router) => {
    console.log(id);
      try {
        const response = await request.get('api/survey/getStatistic', {params:{ id:id }});
        console.log(response.data);
        localStorage.setItem('staticsId', response.data.id);
        router.push('/Statistics');
        if (response.code === "200") {
          localStorage.setItem('staticsId', response.data.id);
          ElMessage.success('打开成功！');
          console.log(staticsId);
          router.push('/Statistics');
        } else {
          ElMessage.error('打开失败！');
          //router.push('/Statistics');
        }
      } catch (err) {
        console.log(err);
      }
    };

    const touserSurvey =async (Rid:number)=>{
      console.log(Rid);
      const config_post = {
        method: 'put',
        url: 'api/survey/update',
        data: {
          id:Rid,
          status:1,
        }
      };
      ElMessageBox.confirm('确定仅对用户修改该问卷?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await request.put('api/survey/update',null,{
            params:{
              id:Rid,
              status:1,
            }
          }
          ).then(res=>{
          if (response.code === '200') {
            console.log(/*config_delete.data.id*/"3333");
          } else {
            ElMessage.error(response.msg || '发布失败');
          }
        })
      } 
        catch (error) {
          ElMessage.success('修改问卷状态成功');
          console.log(Rid);
          load();
        }
      }).catch(() => {
        ElMessage.info('已取消发布');
      });
    };

    const postSurvey = async (Rid:number)=>{
      console.log(Rid);
      const config_post = {
        method: 'put',
        url: 'api/survey/update',
        data: {
          id:Rid,
          status:2,
        }
      };
      ElMessageBox.confirm('确定发布该问卷?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await request.put('api/survey/update',null,{
            params:{
              id:Rid,
              status:2,
            }
          }
          ).then(res=>{
          if (response.code === '200') {
            console.log(/*config_delete.data.id*/"3333");
          } else {
            ElMessage.error(response.msg || '发布失败');
          }
        })
      } 
        catch (error) {
          ElMessage.success('问卷发布成功');
          console.log(Rid);
          load();
        }
      }).catch(() => {
        ElMessage.info('已取消发布');
      });
    };

    const UnpostSurvey = async (Rid:number)=>{
      console.log(Rid);
      const config_unpost = {
        method: 'put',
        url: 'api/survey/update',
        data: {
          id:Rid,
          status:3,
        }
      };
      ElMessageBox.confirm('确定取消发布该问卷?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '还是发布着吧😛',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await request.put('api/survey/update',null,{
            params:{
              id:Rid,
              status:3,
            }
          }
          ).then(res=>{
          if (response.code === '200') {
            console.log(/*config_delete.data.id*/"4444");
          } else {
            ElMessage.error(response.msg || '取消发布失败');
          }
        })
      } 
        catch (error) {
          ElMessage.success('问卷已取消发布');
          console.log(Rid);
          load();
        }
      }).catch(() => {
        ElMessage.info('仍然继续发布');
      });
    };

    const openRenameDialog = (row: Questionnaire) => {
      console.log('Opening rename dialog for:', row); // 调试信息
      renameForm.value.id = row.id;
      renameForm.value.title = row.title;
      console.log('renameForm:', renameForm.value); // 调试信息
      //renameDialogVisible.value = true;
      renameDialogVisible=true;
      console.log('renameDialogVisible:', renameDialogVisible.value); // 调试信息
};

    const toallSurvey = async (Rid:number)=>{
      console.log(Rid);
      const config_post = {
        method: 'put',
        url: 'api/survey/update',
        data: {
          id:Rid,
          status:2,
        }
      };
      ElMessageBox.confirm('确定对所有人开放该问卷?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await request.put('api/survey/update',null,{
            params:{
              id:Rid,
              status:2,
            }
          }
          ).then(res=>{
          if (response.code === '200') {
            console.log(/*config_delete.data.id*/"3333");
          } else {
            ElMessage.error(response.msg || '发布失败');
          }
        })
      } 
        catch (error) {
          ElMessage.success('修改问卷状态成功');
          console.log(Rid);
          load();
        }
      }).catch(() => {
        ElMessage.info('已取消修改问卷状态');
      });
    };


    const submitRename = async () => {
      const { id, title } = renameForm.value;
      try {
        const response = await request.put('api/survey/update', null, {
          params: {
            id:id,
            title:title,
          },
        });
        if (response.code === '200') {
          ElMessage.success('问卷名称修改成功');
          load();
          renameDialogVisible.value = false;
        } else {
          ElMessage.error(response.msg || '名称修改失败');
        }
      } catch (error) {
        ElMessage.error('名称修改失败');
      }
    };

    const tableRowQuestionnaire = ({ row }: { row: Questionnaire }) => {
      if (row.status === 1) {
        return 'warning-row';
      } else if (row.status === 2) {
        return 'success-row';
      }
      return '';
    };

    const formatStatus = (row: Questionnaire) => {
      if(row.status===2){return '已发布';}
      if(row.status===0){return '未发布';}
      if(row.status===3){return '已截止';}
      if(row.status===1){return '仅对用户开放';}
    };

    load();

    return {
      tableData,
      deleteSurvey,
      tableRowQuestionnaire,
      formatStatus,
      postSurvey,
      UnpostSurvey,
      openRenameDialog,
      submitRename,
      renameDialogVisible,
      renameForm,
      extendedTableData,
      openRename,
      handleTitleBlur,
      cancelEdit,
      statisticSurvey,
      touserSurvey,
      toallSurvey,
    };
  }
});
</script>

<style>
.editable-title {
  cursor: pointer;
  padding: 2px;
  border: 1px solid transparent;
}
.editable-title:focus,
.editable-title:hover {
  border-color: #409eff;
}

.editable-input {
  margin-left: 4px;
  padding: 2px;
  border: 1px solid #dcdfe6;
  outline: none;
  border-radius: 4px;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-dialog {
  z-index: 9999 !important; /* 确保对话框在前面显示 */
}
</style>